import java.util.ArrayList;
import java.util.List;

/**
 *解释器模式
 */
public class InterpreterPattern {
    public static void main(String[] args) {
        String context = "a+b+c";
        OrExpression orExpression = new OrExpression();
        orExpression.add(new TerminalExpression("a"));
        orExpression.add(new TerminalExpression("b"));
        orExpression.add(new TerminalExpression("c"));
//        expression.interpret(context);

        Interpreter expression = new Interpreter(orExpression);
        expression.interpret(context);
    }
}
// 非终结符表达式
abstract class Expression {
    public abstract void interpret(String context);
}

// 终结符表达式
class TerminalExpression extends Expression {
    private String value;

    public TerminalExpression(String value) {
        this.value = value;
    }

    @Override
    public void interpret(String context) {
        System.out.println("TerminalExpression: " + value);
    }
}
// 非终结符表达式
class OrExpression extends Expression {
    private List<Expression> expressions = new ArrayList<>();

    public void add(Expression expression) {
        expressions.add(expression);
    }
    @Override
    public void interpret(String context) {
        for (Expression expression : expressions) {
            expression.interpret(context);
        }
    }
}

// 解释器
class Interpreter  {
    private Expression expression;
    public  Interpreter(Expression expression) {
        this.expression = expression;
    }
    public  void interpret(String context) {
        expression.interpret(context);
    }
}